package cn.zwx.common.captcha.core;


import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.zwx.common.captcha.config.CaptchaProperties;
import cn.zwx.common.captcha.enums.CaptchaType;
import cn.zwx.common.captcha.domain.CaptchaEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import javax.annotation.Resource;

/**
 * @author zhangwenxue
 */
@EnableConfigurationProperties({CaptchaProperties.class})
public class CaptchaServiceImpl implements CaptchaService{

    public static final String BASE64_PREFIX = "data:image/jpeg;base64,";
    @Resource
    private CaptchaProperties captchaProperties;


    @Override
    public CaptchaEntity generateCode(Boolean base64Prefix) {
        // 生成验证码
        CaptchaType captchaType = captchaProperties.getType();
        boolean isMath = CaptchaType.MATH == captchaType;
        Integer length = isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
        CodeGenerator codeGenerator = ReflectUtil.newInstance(captchaType.getClazz(), length);
        AbstractCaptcha captcha = SpringUtil.getBean(captchaProperties.getCategory().getClazz());
        captcha.setGenerator(codeGenerator);
        captcha.createCode();
        String code = captcha.getCode();
        if (isMath) {
            ExpressionParser parser = new SpelExpressionParser();
            Expression exp = parser.parseExpression(StringUtils.remove(code, "="));
            code = exp.getValue(String.class);
        }
        return new CaptchaEntity(code,base64Prefix?BASE64_PREFIX+captcha.getImageBase64():captcha.getImageBase64());
    }

    @Override
    public CaptchaEntity generateCode(Boolean base64Prefix,Integer length) {
        // 生成验证码
        CaptchaType captchaType = captchaProperties.getType();
        CodeGenerator codeGenerator = ReflectUtil.newInstance(captchaType.getClazz(), length);
        AbstractCaptcha captcha = SpringUtil.getBean(captchaProperties.getCategory().getClazz());
        captcha.setGenerator(codeGenerator);
        captcha.createCode();
        String code = captcha.getCode();
        if ( CaptchaType.MATH == captchaType) {
            ExpressionParser parser = new SpelExpressionParser();
            Expression exp = parser.parseExpression(StringUtils.remove(code, "="));
            code = exp.getValue(String.class);
        }
        return new CaptchaEntity(code,base64Prefix?BASE64_PREFIX+captcha.getImageBase64():captcha.getImageBase64());
    }
}
